package com.youzi.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.youzi.Logger;
import com.youzi.constant.Contstants;
import com.youzi.util.GoogleTranslateUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * 控制器
 * @author tangyouzhi
 */
public class TranslateAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent event) {
        Logger.init(this.getClass().getSimpleName(), 1);
        executeTranslate(event);
    }

    /**
     * 执行翻译操作
     * @param event
     */
    public void executeTranslate(AnActionEvent event){
        final Editor mEditor = (Editor) event.getData(PlatformDataKeys.EDITOR);
        if (null == mEditor) {
            return;
        }
        final SelectionModel selectionModel = mEditor.getSelectionModel();
        String selectText = selectionModel.getSelectedText();
        if (null != selectText && !"".equals(selectText.trim())) {
            selectText = selectText.replaceAll("\r|\n|/|\\*", "").trim();
            if (selectText.trim().length() <= Contstants.MAX_FANYI_SIZE) {
                try {
                    Pattern p = compile("[\u4e00-\u9fa5]");
                    Matcher m = p.matcher(selectText.trim());
                    String opeName = m.find() ? Contstants.CN_TO_EN : Contstants.EN_TO_CN;
                    String result = GoogleTranslateUtil.translate(selectText, opeName, mEditor);
                    if (null == result) {
                        Logger.error("翻译错误,请重试!");
                        return;
                    }
                    Logger.info(opeName, result);
                } catch (Exception e) {
                    Logger.error("程序异常,请重试!");
                }
            } else {
                Logger.error("单次翻译长度不可超过" + Contstants.MAX_FANYI_SIZE + ".");
            }
        }
    }
}
